/*
 * @Author : restyhap
 * @Date   : 2023-01-20 19:15:27
 * @LastEditors: restyhap
 * @LastEditTime: 2023-02-12 09:30:05
 */
const vscode = require("vscode");
const { tagProcess } = require("./changeTag.js")

/**
 * 根据不同文件选择不同的处理语句方式
 * @param {*} data 需要处理的JSON对象
 * @param {*} text 需要处理的字符串
 * @returns 处理后的字符串
 */
function insertProcess(data, text) {
  // 1. 获取字符串的前缀空格的数量
  let prefixCount = text.length - text.replace(/^\s*/, "").length;

  // 2. 添加前缀字符串
  let prefix = "";
  for (let i = 0; i < prefixCount; i++) {
    prefix += " ";
  }
  // 4.1.1 后缀是.log/.sout/.pn....
  let currentText = text.trim().replace(data.suffix, "");

  if (text.includes(data.suffix)) {
    let textArray = data.print.split("content");
    if (!text.includes(textArray[0])) {
      if (currentText.includes("\"")) {
        currentText = currentText.replace(/\"/g, "");
        text = prefix + `${textArray[0]}\" ${currentText} ======== ${currentText} \"${textArray[1]}`;
      } else {
        switch (data.suffix) {
          case ".log":
          case ".log":
          case ".sout":

            text = prefix + `${textArray[0]}\" ${currentText} ======== \" ${data.connect} ${currentText}${textArray[1]}`;
            break;
          case ".pn":
            text = prefix + `${textArray[0]}\" ${currentText} ======== {}\"${data.connect} ${currentText}${textArray[1]}`;
            break;
          default:
            text = prefix + text + "\t insertProcess() : default process";
            break;
        }
      }

    } else {
      return text;
    }
  }
  return text;
}

/**
 * vue 切换字符串的方法
 * @param {vscode.TextEditor} textEditor
 * @param {*} data
 */
function insertVueProcess(textEditor, data) {
  let doc = textEditor.document;  // 获取当前文档

  let scriptObj = getStartAndEndLine(doc, "script");

  let templateObj = getStartAndEndLine(doc, "template");

  // 获取当前行
  let currentLine = textEditor.selection.active.line;
  // 获取当前行文字
  let text = textEditor.document.lineAt(currentLine).text;

  if (currentLine < scriptObj.end && currentLine > scriptObj.start) {
    // script 处理
    text = insertProcess(data, text);
  } else if (currentLine < templateObj.end && currentLine > templateObj.start) {
    // html 处理
    text = tagProcess(text);
  } else {
    text = text + "  ";
  }
  return text;
}


/**
 * 获取起始和结束位置的方法
 * @param {vscode.TextDocument} doc 获取获取开始和结束的文档
 * @param {string} content 获取以内容为行数的分界点
 */
function getStartAndEndLine(doc, content) {
  let start = 0;
  let end = 0;
  let count = doc.lineCount; // 获取当前文档有多少行
  let num = 0;
  for (let i = 0; i < count; i++) {
    let text = doc.lineAt(i).text;
    if (text.includes(content)) {
      if (num == 0) {
        start = i;
        num++;
      } else {
        end = i;
      }
    }
  }
  return { start: start, end: end }
}

module.exports = {
  insertProcess,
  insertVueProcess,
};
